package com.ren.service.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ren.common.exception.BusinessException;
import com.ren.common.result.ResponseEnum;
import com.ren.service.base.utils.JwtUtils;
import com.ren.service.core.mapper.UserAccountMapper;
import com.ren.service.core.mapper.UserInfoMapper;
import com.ren.service.core.mapper.UserLoginRecordMapper;
import com.ren.service.core.model.po.UserAccountPO;
import com.ren.service.core.model.po.UserInfoPO;
import com.ren.service.core.model.po.UserLoginRecordPO;
import com.ren.service.core.model.vo.*;
import com.ren.service.core.service.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author RenGaoshuai
 * @date 2023/8/8 10:20
 * @description
 */
@Service
@Slf4j
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserLoginRecordMapper userLoginRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterReqVO reqVO) {
        //该手机号是否被注册过
        LambdaQueryWrapper<UserInfoPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfoPO::getMobile, reqVO.getMobile())
                .eq(UserInfoPO::getDeleted, false);
        UserInfoPO queryPO = userInfoMapper.selectOne(wrapper);
        if (Objects.nonNull(queryPO)) {
            throw new BusinessException(ResponseEnum.MOBILE_EXIST_ERROR);
        }

        //用户信息
        UserInfoPO savePo = BeanUtil.copyProperties(reqVO, UserInfoPO.class);
        savePo.setUpdateTime(LocalDateTime.now());
        savePo.setCreateTime(LocalDateTime.now());
        savePo.setDeleted(false);
        savePo.setStatus(1);
        userInfoMapper.insert(savePo);

        //创建会员账户
        UserAccountPO userAccount = new UserAccountPO();
        userAccount.setUserId(savePo.getId());
        userAccount.setUpdateTime(LocalDateTime.now());
        userAccount.setCreateTime(LocalDateTime.now());
        userAccount.setDeleted(false);
        userAccountMapper.insert(userAccount);
    }

    @Override
    public LoginRespVO login(LoginReqVO reqVO, String remoteAddr) {
        String mobile = reqVO.getMobile();
        Integer userType = reqVO.getUserType();
        //校验用户
        LambdaQueryWrapper<UserInfoPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfoPO::getMobile, mobile)
                .eq(UserInfoPO::getUserType, userType)
                .eq(UserInfoPO::getDeleted, false);
        UserInfoPO queryUserInPO = userInfoMapper.selectOne(wrapper);
        if (Objects.isNull(queryUserInPO)) {
            throw new BusinessException(ResponseEnum.LOGIN_MOBILE_ERROR);
        }

        //记录登录日志
        UserLoginRecordPO saveRecord = new UserLoginRecordPO();
        saveRecord.setUserId(queryUserInPO.getId());
        saveRecord.setUpdateTime(LocalDateTime.now());
        saveRecord.setCreateTime(LocalDateTime.now());
        saveRecord.setDeleted(false);
        saveRecord.setIp(remoteAddr);
        userLoginRecordMapper.insert(saveRecord);

        //生成token
        String token = JwtUtils.createToken(queryUserInPO.getId(), queryUserInPO.getName());

        //返回数据
        LoginRespVO userInfoRespVO = BeanUtil.copyProperties(queryUserInPO, LoginRespVO.class);
        userInfoRespVO.setToken(token);

        return userInfoRespVO;
    }

    @Override
    public IPage<UserInfoPO> listPage(Page<UserInfoPO> pageParam, UserInfoQueryReqVO reqVO) {
        if (reqVO == null) {
            return userInfoMapper.selectPage(pageParam, null);
        }

        String mobile = reqVO.getMobile();
        Integer status = reqVO.getStatus();
        Integer userType = reqVO.getUserType();
        QueryWrapper<UserInfoPO> wrapper = new QueryWrapper<>();

        wrapper
                .eq(StrUtil.isNotBlank(mobile), "mobile", mobile)
                .eq(status != null, "status", status)
                .eq(userType != null, "user_type", userType);
        return userInfoMapper.selectPage(pageParam, wrapper);
    }

    @Override
    public int lock(UserInfoLockReqVO reqVO) {
        UserInfoPO updatePO = BeanUtil.copyProperties(reqVO, UserInfoPO.class);
        return userInfoMapper.updateById(updatePO);
    }

    @Override
    public boolean checkMobile(String mobile) {
        LambdaQueryWrapper<UserInfoPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfoPO::getMobile, mobile)
                .eq(UserInfoPO::getDeleted, false);
        return userInfoMapper.selectCount(wrapper) > 0;
    }
}
